<?php

namespace app\common\model\mysql;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Exception;
use think\Model;
use think\model\relation\BelongsTo;

class AdminUser extends BaseModel
{
    protected $schema=[
        'id'=>'int',
        'username'=>'varchar',
        'password'=>'char',
        'real_name'=>'varchar',
        'roles'=>'int',
        'area_id'=>'int',
        'last_login_ip'=>'varchar',
        'last_login_time'=>'int',
        'phone'=>'varchar',
        'status'=>'tinyint',
        'create_time'=>'int',
        'update_time'=>'int',
    ];

    public function role(): BelongsTo
    {
        return $this->belongsTo(AdminRole::class,'roles');
    }

    /**
     * 通过username获取后台管理员信息
     * @param $username
     * @return array|false|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAdminUserByUsername($username)
    {
        if (empty($username)) {
            return false;
        }

        $where = [
            "username" => trim($username),
        ];
        return $this->where($where)->find();
    }

    /**
     * 根据当前用户id查询用户信息
     * @param $id
     * @return AdminUser|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAdminUserById($id){
        $bField='id,rules,role_name';
        return $this->field(['id','real_name','roles','area_id'])->with(['role'=>function($query) use ($bField){
            $query->field($bField);
        }])->where(['id'=>$id,'status'=>config("status.mysql.table_normal")])->find();
    }

    /**
     * 获取分页列表
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTableList($where,$page,$limit): array
    {
        if(!empty($page)&&!empty($limit)){
            $this->page($page,$limit);
        }
        $bField='id,role_name';
        $list=$this->field(['id','username','real_name','roles','last_login_ip','last_login_time','status','create_time','update_time','phone','area_id'])->with(['role'=>function($query) use ($bField){
            $query->field($bField);
        }])->where($where)->order('id desc')->select();
        $list=$list->isEmpty()?[]:$list->toArray();
        $count=$this->with(['role'=>function($query) use ($bField){
            $query->field($bField);
        }])->where($where)->count();
        return ['count'=>$count,'list'=>$list];
    }
}
